from forest.api import Command, get_tool

class Systemd(Command):
    ''' Enables/disables service resources and sets the default target if specified.

        .. describe:: default_target

            Default target name.
    '''
    __register__ = 'commands.setup.Systemd'

    def run(self, config, set_default = True):

        installtree = config.get_install_root()

        if set_default:
            default_target = config.get('default_target', 'multi-user')

        # XXX: we chroot for now due to the way the systemd tool works.. this should be fixed (NS)

            #TODO could get rid of this chroot - set_default_target very simple
            with get_tool('system.chroot')(installtree):
                get_tool('systemd.set_default_target')(default_target)

        systemd = get_tool('systemd.Systemd')(installtree)

        for service in config.get_resources().iter_by_type('service'):
            curr_service = systemd.get_service(service.get_name())
            if not curr_service:
                continue

            if service.get_enabled():
                curr_service.enable()
            elif service.get_enabled() is not None:
                curr_service.disable()



